package com.dbsop.common.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class FieldUtils {


    /**
     * 根据字段名称获取值
     * @param object
     * @param fieldName
     * @return
     */
    public static Object getFieldValue(Object object,String fieldName){
        Field fieldSupper = getFieldSupper(fieldName, object.getClass());
        if (fieldSupper == null)return null;
        return getFieldValue(object,fieldSupper);
    }

    /**
     * 获取字段值
     * @param object
     * @param field
     * @return
     */
    public static Object getFieldValue(Object object, Field field){
        field.setAccessible(true);
        try {
            return field.get(object);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取所有字段
     * @param clazz
     * @return
     */
    public static List<Field> getFieldListSupper(Class clazz){
        List<Field> fields = new ArrayList<Field>();
        while (clazz !=null){
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        return fields;
    }

    /**
     * 获取指定字段
     * @param fieldName
     * @param clazz
     * @return
     */
    public static Field getFieldSupper(String fieldName,Class clazz){
        Field declaredField = null;
        try {
            declaredField = clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) { }
        if (declaredField == null) {
            if (clazz.getSuperclass() == null) return null;
            return getFieldSupper(fieldName, clazz.getSuperclass());
        }
        return declaredField;

    }



    public static String[] converList(Collection<String> values){
        String[] strArr = new String[values.size()];
        values.toArray(strArr);
        return strArr;
    }

}
